<?php
// +----------------------------------------------------------------------
// | wttai [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.wttai.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 老司机 <wutongtai@wttai.com> <http://www.wttai.com>
// +----------------------------------------------------------------------

namespace Common\Model;
use Think\Model;

/**
 * 文档基础模型
 */
class DocumentModel extends BaseModel{

    /* 自动验证规则 */
    protected $_validate = array(
        array('name', '/^[a-zA-Z]\w{0,30}$/', '文档标识不合法', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),
        array('name', '', '标识已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_BOTH),
        array('title', 'require', '标题不能为空', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),
        array('category_id', 'require', '分类不能为空', self::MUST_VALIDATE , 'regex', self::MODEL_INSERT),
        array('category_id', 'require', '分类不能为空', self::EXISTS_VALIDATE , 'regex', self::MODEL_UPDATE),
        array('category_id,type', 'check_category', '内容类型不正确', self::MUST_VALIDATE , 'function', self::MODEL_INSERT),
        array('category_id', 'check_category', '该分类不允许发布内容', self::EXISTS_VALIDATE , 'function', self::MODEL_BOTH),
        array('model_id,category_id,pid', 'check_category_model', '该分类没有绑定当前模型', self::MUST_VALIDATE , 'function', self::MODEL_INSERT),
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('uid', 'session', self::MODEL_INSERT, 'function', 'user_auth.uid'),
        array('title', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
        array('description', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
        array('root', 'getRoot', self::MODEL_BOTH, 'callback'),
        array('attach', 0, self::MODEL_INSERT),
        array('view', 0, self::MODEL_INSERT),
        array('comment', 0, self::MODEL_INSERT),
        array('extend', 0, self::MODEL_INSERT),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        //array('reply_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', 'getStatus', self::MODEL_BOTH, 'callback'),
    );

    public $page = '';

    /**
     * 获取文档列表
     * @param  integer  $category 分类ID
     * @param  string   $order    排序规则
     * @param  integer  $status   状态
     * @param  boolean  $count    是否返回总数
     * @param  string   $field    字段 true-所有字段
     * @return array              文档列表
     * @param  integer  $site_id  站点id
     */
    public function lists($category,$site_id=1, $order = '`id` DESC', $status = 1, $field = true){
        //查询出当前站点的数据
        $aids=getSetArticle($site_id);
        $map['id']=array('in',$site_id);
        $map = $this->listMap($category, $status);
        return $this->field($field)->where($map)->order($order)->select();
    }

    /**
     * 计算列表总数
     * @param  number  $category 分类ID
     * @param  integer $status   状态
     * @return integer           总数
     */
    public function listCount($category, $status = 1){
        
        $map = $this->listMap($category, $status);
        return $this->where($map)->count('id');
    }

    /**
     * 获取详情页数据
     * @param  integer $id 文档ID
     * @return array       详细数据
     */
    public function detailByname($name, $site_id = SITE_ID,$id){
       
        /* 获取基础数据 */
        //通过标签id查找文章
        if(is_numeric($name)){
           $article_id= M('ArticleTags')->where('tags_id='.$name)->field('article_id')->select();
           $article_id=array_column($article_id, 'article_id');
           $where=array('article_id'=>array('in',$article_id),'site_id'=>$site_id);
           $article_id=M('ArticleSite')->where($where)->field('article_id')->select();
           $article_id=array_column($article_id, 'article_id');
           //dump($article_id);exit;
           shuffle($article_id);
           $info=$this->field(true)->where('id='.$article_id[0])->find();
           
        }else{
            if($id){
                $info = $this->field(true)->where(array('id'=>$id))->find();
            }else{
                $info = $this->field(true)->where(array('pin_yin'=>$name))->find();
                if(!$info){
                    $info=$this->field(true)->where(array('name'=>$name))->find();  //name属性查询
                }
            }
           
           
        }
        
        //dump($info);exit;
        if ( !$info ) {
            $this->error = '文档不存在';
            return false;
        }elseif(!(is_array($info)) || 1 != $info['status']){
            $this->error = '文档被禁用或已删除！';
            return false;
        }
      
        $id = $info['id'];
       
        $bind_count = D('ArticleSite')->where(array('article_id'=> $id, 'site_id' => $site_id))->count();
        
        if ($bind_count < 1) {
            $this->error = '无权访问此文章';
            return false;
        }
        
        /* 获取模型数据 */
        $logic  = $this->logic($info['model_id']);
        $detail = $logic->detail($id); //获取指定ID的数据
        if($detail['deal_content']){       
            //检测里面的图片是否已经失效,若第一张已经失效，则重新获取
           // $map=img_exists($detail['deal_content']);
            /* if(!$map){
                $detail['deal_content']=deal_content_img($detail['content']);
                M('DocumentArticle')->where(array('id'=>$id))->save($detail);
            } */
            $detail['content']=$detail['deal_content'];
        }else{
            $deal_content['deal_content']=deal_content_img($detail['content']);
            M('DocumentArticle')->where(array('id'=>$id))->save($deal_content);
            $detail['content']=$deal_content['deal_content'];
        }
       
       
        if(!$detail){
            $this->error = $logic->getError();
            return false;
        }
        return array_merge($info, $detail);
    }
    
    
    /**
     * 获取详情页数据
     * @param  integer $id 文档ID
     * @return array       详细数据
     */
    public function detail($id){
        /* 获取基础数据 */
        $info = $this->field(true)->find($id);

        if ( !$info ) {
            $this->error = '文档不存在';
            return false;
        }elseif(!(is_array($info)) || 1 != $info['status']){
            $this->error = '文档被禁用或已删除！';
            return false;
        }
        /* 获取模型数据 */
        $logic  = $this->logic($info['model_id']);
        $detail = $logic->detail($id); //获取指定ID的数据
        if(!$detail){
            $this->error = $logic->getError();
            return false;
        }
        return array_merge($info, $detail);
    }

    /**
     * 返回前一篇文档信息
     * @param  array $info 当前文档信息
     * @return array
     */
    public function prev($info){
        $map = array(
            'a.create_time'          => array('egt', $info['create_time']),
            'a.id'=>array('gt',$info['id']),
            'pid'		  => 0,
            'category_id' => $info['category_id'],
            'status'      => 1,
            'create_time' => array('lt', NOW_TIME),
            '_string'     => 'deadline = 0 OR deadline > ' . NOW_TIME,  			
        );
        $map['b.`site_id`'] = C('SITE');
        /* 返回前一条数据 */
        $pre=$this->alias('a')->field('a.*')->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->order('create_time Asc,a.id ASC')->find();
        
        if($pre){
            return $pre;
        }else{
           return 1;
        }
    }

    /**
     * 获取下一篇文档基本信息
     * @param  array    $info 当前文档信息
     * @return array
     */
    public function next($info){
        $map = array(
            'a.create_time'          => array('elt', $info['create_time']),
            'a.id'=>array('lt',$info['id']),
            'pid'		  => 0,
            'category_id' => $info['category_id'],
            'status'      => 1,
            'create_time' => array('lt', NOW_TIME),
            '_string'     => 'deadline = 0 OR deadline > ' . NOW_TIME,  			
        );
        $map['b.`site_id`'] = C('SITE');
        /* 返回下一条数据 */
        $res=$this->alias('a')->field('a.*')->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->order('a.create_time DESC,a.id DESC')->find();
        if($res){
            return $res;
        }else{
            return 1;
        }
    }

    /**
     * 获取到最热资讯
     */
    public function getSiteHotDocument($site_id=SITE_ID, $limit=10){
        $map['b.`site_id`'] = $site_id;
        $map['a.`status`'] = 1;
        $order="view desc,level desc";
        return  $this->alias('a')->field('a.*')->order($order)->limit($limit)->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->select();
        
    }
    
    public function update(){
        /* 检查文档类型是否符合要求 */
        $Model = new \Admin\Model\DocumentModel();
        $res = $Model->checkDocumentType( I('type'), I('pid') );
        if(!$res['status']){
            $this->error = $res['info'];
            return false;
        }

        /* 获取数据对象 */
        $data = $this->field('pos,display', true)->create();
        if(empty($data)){
            return false;
        }

        /* 添加或新增基础内容 */
        if(empty($data['id'])){ //新增数据
            $id = $this->add(); //添加基础内容

            if(!$id){
                $this->error = '添加基础内容出错！';
                return false;
            }
            $data['id'] = $id;
        } else { //更新数据
            $status = $this->save(); //更新基础内容
            if(false === $status){
                $this->error = '更新基础内容出错！';
                return false;
            }
        }

        /* 添加或新增扩展内容 */
        $logic = $this->logic($data['model_id']);
        if(!$logic->update($data['id'])){
            if(isset($id)){ //新增失败，删除基础数据
                $this->delete($data['id']);
            }
            $this->error = $logic->getError();
            return false;
        }

        //内容添加或更新完成
        return $data;

    }

    /**
     * 获取段落列表
     * @param  integer $id    文档ID
     * @param  integer $page  显示页码
     * @param  boolean $field 查询字段
     * @param  boolean $logic 是否查询模型数据
     * @return array
     */
    public function part($id, $page = 1, $field = true, $logic = true){
        $map  = array('status' => 1, 'pid' => $id, 'type' => 3);
        $info = $this->field($field)->where($map)->page($page, 10)->order('id')->select();
        if(!$info) {
            $this->error = '该文档没有段落！';
            return false;
        }

        /* 不获取内容详情 */
        if(!$logic){
            return $info;
        }

        /* 获取内容详情 */
        $model = $logic = array();
        foreach ($info as $value) {
            $model[$value['model_id']][] = $value['id'];
        }
        foreach ($model as $model_id => $ids) {
            $data   = $this->logic($model_id)->lists($ids,SITE_ID);
            $logic += $data;
        }

        /* 合并数据 */
        foreach ($info as &$value) {
            $value = array_merge($value, $logic[$value['id']]);
        }

        return $info;
    }

    /**
     * 获取指定文档的段落总数
     * @param  number $id 段落ID
     * @return number     总数
     */
    public function partCount($id){
        $map = array('status' => 1, 'pid' => $id, 'type' => 3);
        return $this->where($map)->count('id');
    }

    /**
     * 获取对应网站推荐位数据列表
     * @param  number  $pos      推荐位 1-列表推荐，2-频道页推荐，4-首页推荐
     * @param  array   $pos      推荐位基础参数同上 如array(1,2,3,4,5)
     * @param  number  $category 分类ID
     * @param  number  $limit    列表行数
     * @param  boolean $filed    查询字段
     * @return array             数据列表
     */
    public function position($pos, $category = null, $limit = null, $field = true){
        $map = $this->listMap($category, 1, $pos);
        /* 设置列表数量 */
        is_numeric($limit) && $this->limit($limit);
        $map['b.`site_id`'] = C('SITE');
        $map['a.`status`'] = 1;
        /* 读取数据 */
        //return $this->field($field)->where($map)->select();
        return $this->alias('a')->field('a.*')->order('a.id DESC')->page($p, $limit)->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->select();
    }
    /**
     * 获取对应网站对应文章的相关文章
     * @param  number  $id  文章id
     * @param  number  $site_id  站点id
     *  @param  number $number  文章数量
     */
    public function relativeArticle($id,$site_id,$number=10){
      //获取这个文章的相关标签
      //return 12;
      $tags_id= D('Tags')->getTags($id);
      if($tags_id){
         $tags_id=array_column($tags_id, 'id');
         
         //查询出与篇文章的标签有共同标签的文章
         
         $where['tags_id']=array('in',$tags_id);
         $article=M('ArticleTags')->where($where)->field('article_id')->select();
         $article=array_column($article, 'article_id');
         $article=array_unique($article);
         //在之前前提下查询出同站的文章
         $map['a.id']=array('in',$article);
         $map['_string']="  a.id != $id";
         $map['b.site_id']=$site_id;
         $relative=$this->alias('a')->field('a.id')->order('a.create_time DESC')->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->limit($number)->select();
         $this->addCovel($relative);//增加封面
         $relate_ids=array_column($relative, 'id');
         $relate_map['a.id']=array('in',$relate_ids);
         $relative=$this->alias('a')->field('a.title,a.name,a.pin_yin,a.id,a.create_time,a.cover_id,a.view,a.description')->order('a.id DESC')->where($relate_map)->select();
         return $relative;
      }
      return 1;
      //   
    }
    /**
     * 获取数据状态
     * @return integer 数据状态
     * @author huajie <laoshiji@wttai.com>
     */
    protected function getStatus(){
        $cate = I('post.category_id');
        $check = M('Category')->getFieldById($cate, 'check');
        if($check){
            $status = 2;
        }else{
            $status = 1;
        }
        return $status;
    }

    /**
     * 获取根节点id
     * @return integer 数据id
     * @author huajie <laoshiji@wttai.com>
     */
    protected function getRoot(){
        $pid = I('post.pid');
        if($pid == 0){
            return 0;
        }
        $p_root = $this->getFieldById($pid, 'root');
        return $p_root == 0 ? $pid : $p_root;
    }

    /**
     * 获取扩展模型对象
     * @param  integer $model 模型编号
     * @return object         模型对象
     */
    private function logic($model){
        $name  = parse_name(get_document_model($model, 'name'), 1);
        $class = is_file(MODULE_PATH . 'Logic/' . $name . 'Logic' . EXT) ? $name : 'Base';
        $class = MODULE_NAME . '\\Logic\\' . $class . 'Logic';
        return new $class($name);  		
    }

    /**
     * 设置where查询条件
     * @param  number  $category 分类ID
	 * @param  integer $status   状态
     * @param  number  $pos      推荐位
     * @return array             查询条件
     */
    private function listMap($category, $status = 1, $pos = null){
        /* 设置状态 */
        $map = array('status' => $status, 'pid' => 0);

        /* 设置分类 */
        if(!is_null($category)){
            if(is_numeric($category)){
                $map['category_id'] = $category;
            } else {
                $map['category_id'] = array('in', str2arr($category));
            }
        }

        $map['create_time'] = array('lt', NOW_TIME);
         /* 设置推荐位 */
        if(is_numeric($pos)){
            $map[] = "position & {$pos} = {$pos}";
        } else if (is_array($pos)){
            $map['position'] = array('in',$pos);
        }
        $map['_string']     = 'deadline = 0 OR deadline > ' . NOW_TIME;

        return $map;
    }

    /**
     * 获取站点所有文章数量
     * 
     * @param type $site_id
     * @return type
     * 
     */
    public function getSiteArticleCount($site_id)
    {
        $map['b.`site_id`'] = $site_id;
        $map['a.`status`'] = 1;
        return  $this->alias('a')->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->count();
    }
    
    /**
     * 获取站点所有文章列表
     * 
     * @param type $site_id
     * @return type
     * 
     */
    public function getSiteArticleList($site_id, $p=1, $limit=20)
    {
        $map['a.id']=array('gt',0);
        $map['b.`site_id`'] = $site_id;
        $map['a.`status`'] = 1;
        return  $this->alias('a')->field('a.*')->order('a.create_time DESC,a.id DESC')->page($p, $limit)->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->select();
    }
    /**
     * 获取站点最新的文章列表
     *
     * @param type $site_id
     * @return type
     *
     */
    public function getSiteNewArticleList($site_id=SITE_ID, $limit=10)
    {
     
        $map['b.`site_id`'] = $site_id;
        $map['a.`status`'] = 1;
       
       return  $this->alias('a')->field('a.*')->order('create_time DESC,a.id DESC')->limit($limit)->join('__ARTICLE_SITE__ AS `b` on a.`id` = b.`article_id`')->where($map)->select();
    }
    
    /** 文章增加封面字段
     *  @paramer $doucment  文章数据
     *   
     */
    public function addCovel($doucment){
        //$where['id']=array('gt',50);
        $ids=array_column($doucment, 'id');
        $where['id']=array('in',$ids);
        
        $DocumentArticle=M('DocumentArticle')->where($where)->field('id,deal_content,content')->select();
        
        foreach($DocumentArticle as $v){
            $document=M('document')->field('cover_id')->where(array('id'=>$v['id']))->find();
            if(!$document['cover_id']){
                if($v['deal_content']){
                    
                    //文章有处理
                    preg_match_all("/src[=\"(\'\s]+([^\"\']+).jpg[\"\)']/i", $v['deal_content'],$matches);
                    $covel_img=$matches[0][0];
                }else{
                    //文章未处理
                    preg_match_all("/src[=\"(\'\s]+([^\"\']+)[\"\)']/i", $v['content'],$matches);
                    //取文章中间的图片
                    $i=floor(count($matches[0])/2);
                    $covel_img=array($matches[0][$i]);
                    //将图片上传到贴图库
                    
                    $covel_img=tietu($covel_img,$v['id']);
                    
                }
                $str=substr($covel_img,5,-1);
              if(img_exist($str)){ 
                  $data['cover_id']=$str;
                  
              }else{
                  if(!$covelimgs){
                      $covelimgs=$this->getCovelByMaterial();//从素材库获取封面图
                     
                  }
                  $index=$v['id']%15+1; 
                  $data['cover_id']=$covelimgs ?$covelimgs[$index]['s_url']  : "";
              }
          
                //$data['cover_id']=(substr($covel_img,5,-1) ?  :$covelimgs[$index]['s_url']);//图片不存在使用默认图片
                M('document')->where(array('id'=>$v['id']))->save($data);
            }
    
        }
    }
    public function getCovelByMaterial(){
        $url=C('SHEQU_DOMAIN')."/index/getfirstimg?p=1";
        $covelimgs=getApiDataByUrl($url,$data);
        return $covelimgs;
    }
    
    
}
